<script lang="ts" setup>
import type { WorkbenchQuickNavItem } from '@vben/common-ui';

import type { DefApplicationModel } from '#/api';

import { computed, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import {
  WorkbenchHeader,
  WorkbenchQuickNav,
  WorkbenchTrends,
} from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { preferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';
import { cloneDeep, isUrl, openWindow } from '@vben/utils';

import { asyncComputed } from '@vueuse/core';
import { TabPane, Tabs } from 'ant-design-vue';

import {
  asyncFindUrlById,
  checkEmployeeHaveApplication,
  findMyApplication,
} from '#/api';
import { useMessage } from '#/hooks/web/useMessage';
import { useAuthStore } from '#/store';

import ApplicationCard from './modules/application-card.vue';
import NoTenant from './modules/no-tenant.vue';
import { quickNavItems, trendItems } from './schemas/index';

const userStore = useUserStore();
const accessStore = useAccessStore();

const authStore = useAuthStore();
const router = useRouter();
const { createMessage, createConfirm } = useMessage();

const activeTab = ref('home');
const data = reactive<{
  applicationList: DefApplicationModel.DefApplicationResultVO[];
}>({
  applicationList: [],
});

// 是否拥有租户
const hasTenant = computed(
  () =>
    userStore.userInfo?.employeeId && userStore.userInfo?.employeeId !== '0',
);

async function navTo(item: DefApplicationModel.DefApplicationResultVO) {
  if (accessStore.applicationId === item?.id) {
    createMessage.warn(`您当前正处于[${item.name}]，无需切换`);
    return;
  }
  if (!item || !item.id) {
    createMessage.error('请选择正确的应用进行切换');
  }
  try {
    // openFullLoading();
    const canJump = await checkEmployeeHaveApplication(item?.id || '');
    if (!canJump) {
      createMessage.warn(
        `对不起，您无该应用访问权限，请联系贵公司管理员开通权限`,
      );
      return '';
    }
    const isOpen = item.url && isUrl(item.url);
    createConfirm({
      iconType: 'warning',
      content: `确定要${isOpen ? '跳转' : '切换'}到应用：【${
        item.name
      }】， 并重新加载其资源吗？`,
      onOk: async () => {
        if (isOpen) {
          window.open(item.url);
        } else {
          const { closeAllTabs } = useTabs();
          closeAllTabs();

          const fetchUserInfoResult = await authStore.fetchUserInfo();

          userStore.setUserInfo(fetchUserInfoResult);

          accessStore.setIsAccessChecked(false);
          accessStore.setApplicationId(item.id as string);
          accessStore.setApplicationName(item.name as string);

          if (accessStore.loginExpired) {
            accessStore.setLoginExpired(false);
          } else {
            createMessage.success(`成功切换到应用：[${item.name}]`);
            router.go(0);
          }
        }
      },
    });
  } finally {
    // closeFullLoading();
  }
}

async function handleDemo(nav: WorkbenchQuickNavItem) {
  if (nav.url?.startsWith('http')) {
    openWindow(nav.url);
    return;
  }
  if (nav.url?.startsWith('/')) {
    router.push(nav.url).catch((error) => {
      console.error('Navigation failed:', error);
    });
  } else {
    console.warn(`Unknown URL for navigation item: ${nav.title} -> ${nav.url}`);
  }
}

onMounted(async () => {
  const result = await findMyApplication({});
  data.applicationList = cloneDeep(result);
});

const avatar = asyncComputed(async () => {
  const url = userStore.userInfo?.avatarId ?? preferences.app.defaultAvatar;
  let realSrc = '';
  if (url && url.startsWith('http')) {
    realSrc = url;
  } else if (url && url.startsWith('data:')) {
    realSrc = url;
  } else {
    realSrc = await loadSrc(url);
  }
  return realSrc;
});

async function loadSrc(fileId: string) {
  if (!fileId) {
    return preferences.app.defaultAvatar;
  }
  const api = asyncFindUrlById;
  const res = await api(fileId);

  return res.code === 0 ? (res.data as string) : preferences.app.defaultAvatar;
}
</script>

<template>
  <div class="p-5">
    <WorkbenchHeader :avatar="avatar">
      <template #title>
        美好的一天, {{ userStore.userInfo?.nickName }}, 开始您一天的工作吧！
      </template>
      <template #description>
        {{ userStore.userInfo?.workDescribe }}
      </template>
      <template #tabs>
        <Tabs
          v-model:active-key="activeTab"
          :tab-bar-style="{ marginBottom: 0 }"
        >
          <TabPane key="home" tab="首页" />
<!--          <TabPane key="about" tab="关于项目" />-->
        </Tabs>
      </template>
    </WorkbenchHeader>

    <div class="mt-5 flex flex-col lg:flex-row" v-show="activeTab === 'home'">
      <div class="mr-4 w-full lg:w-3/5">
        <ApplicationCard
          v-if="hasTenant"
          :current-application-id="accessStore.applicationId"
          :items="data.applicationList"
          title="我的应用"
          @click="navTo"
        />
        <NoTenant v-else />
        <WorkbenchQuickNav
          :items="quickNavItems"
          title="公司产品"
          @click="handleDemo"
          class="mt-5"
        />
      </div>
      <div class="w-full lg:w-2/5">
        <WorkbenchTrends
          class="mt-5 lg:mt-0"
          :items="trendItems"
          title="最新动态"
        />
      </div>
    </div>
<!--    <div class="mt-5 flex flex-col lg:flex-row" v-show="activeTab === 'about'">
      <About />
    </div>-->
  </div>
</template>
